/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Description: Hmfs-tools ssa
 */

#include "compare_ssa.h"

#include <memory>
#include <cinttypes>
#include <cmath>
#include <string>
#include <sys/types.h>

#include "hmfs_log.h"
#include "hmfs_utils.h"
#include "io.h"
#include "securec.h"

namespace OHOS {
namespace Hmfs {
int32_t CompareSsa::CompareSsaArea()
{
    if (ReadSsaArea(srcInfo_)) {
        HMFS_ERROR("Failed to read ssa area.");
        return -1;
    }
    if (ReadSsaArea(dstInfo_)) {
        HMFS_ERROR("Failed to read ssa area.");
        return -1;
    }

    if (memcmp(srcInfo_.ssaBuf.get(), dstInfo_.ssaBuf.get(), ssaBufferSize_)) {
        HMFS_ERROR("ssa not equal, at offset 0x%" PRIx64 ", len = 0x%" PRIx64 "", srcInfo_.ssaOffset, ssaBufferSize_);
    }

    return 0;
}

int32_t CompareSsa::ReadSsaArea(FsData &fsInfo)
{
    fsInfo.ssaOffset = GetLeValue(fsInfo.superBlock->ssaBlockId) * HMFS_BLOCK_SIZE;
    HMFS_INFO("ssaOffset = 0x%" PRIx64 ".", fsInfo.ssaOffset);

    ssaBufferSize_ = (GetLeValue(fsInfo.superBlock->segmentCountInSSA) <<
        GetLeValue(fsInfo.superBlock->logBlksPerSeg)) * HMFS_BLOCK_SIZE;
    fsInfo.ssaBuf = std::make_unique<char[]>(ssaBufferSize_);
    if (DevRead(fsInfo, fsInfo.ssaBuf.get(), fsInfo.ssaOffset, ssaBufferSize_)) {
        HMFS_ERROR("Failed to read ssa area.");
        return -1;
    }

    return 0;
}
} // namespace Hmfs
} // namespace OHOS
